import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MineDialog extends JFrame {
    private JLabel difficultyLabel;      // 挖矿难度标签
    private int difficulty;
    private Chain myBlockChain;
    private String pubKey;
    private JLabel timeCountLabel;       // 挖矿时间标签
    private JButton startMiningButton;   // 启动挖矿线程按钮
    private JButton stopMiningButton;    // 停止挖矿线程按钮
    private Thread miningThread;         // 挖矿线程
    private Thread timeCountTread;
    private boolean miningRunning = false; // 挖矿是否正在进行

    public MineDialog(List<Map.Entry<String, String>> shareDataList, Chain myBlockChain) {
        // 设置窗体的标题
        setTitle("挖矿");
        // 设置窗体的大小
        setSize(400, 300);

        this.myBlockChain = myBlockChain;
        this.pubKey = Utils.getValueByKey(shareDataList,"publicKey");

        // 创建难度和时间标签
        String difficultyStr = Utils.getValueByKey(shareDataList,"difficulty");
        this.difficulty = Integer.parseInt(difficultyStr);
        this.difficultyLabel = new JLabel("挖矿难度: "+difficultyStr);
        this.difficultyLabel.setHorizontalAlignment(JLabel.CENTER);
        this.timeCountLabel = new JLabel("挖矿时间: 0s");
        this.timeCountLabel.setHorizontalAlignment(JLabel.CENTER);

        // 更新链的挖矿难度
        myBlockChain.setDifficulty(this.difficulty);

        // 创建按钮
        this.startMiningButton = new JButton("启动挖矿线程");
        this.stopMiningButton = new JButton("停止挖矿线程");

        // 启动挖矿线程按钮事件监听器
        startMiningButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!miningRunning) {
                    startMining();
                }
            }
        });

        // 停止挖矿线程按钮事件监听器
        stopMiningButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopMining();
            }
        });

        // 创建面板来放置标签和按钮
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3, 1, 10, 10)); // 3行1列的布局
        panel.add(difficultyLabel);
        panel.add(timeCountLabel);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(startMiningButton);
        buttonPanel.add(stopMiningButton);
        panel.add(buttonPanel);

        // 将面板添加到窗体
        add(panel);
        setLocationRelativeTo(null);  // 设置窗体居中显示
    }

    private void startMining() {
        miningRunning = true;
        JOptionPane.showMessageDialog(this, "挖矿已开始！");
        miningThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    myBlockChain.mineBlock(pubKey);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if(miningRunning){
                    miningRunning = false;
                    String newBlockHash = myBlockChain.getLatestBlock().hash;
                    JOptionPane.showMessageDialog(MineDialog.this, "挖矿成功！ 出块哈希为："+newBlockHash);

                    System.out.println(myBlockChain.toString());// 如果需要的话可以做成按钮，显示当前区块链的整体情况
                }
            }
        });
        timeCountTread = new Thread(new Runnable() {
            @Override
            public void run() {
                int timeCount = 0;
                while (miningRunning) {
                    try {
                        timeCountLabel.setText("挖矿时间：" + timeCount + "s");
                        Thread.sleep(1000);
                        timeCount++;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        miningThread.start();
        timeCountTread.start();
    }

    private void stopMining() {
        miningRunning = false;
        if (miningThread != null) {
            miningThread.interrupt();  // 停止线程
        }
        if (timeCountTread != null) {
            timeCountTread.interrupt();  // 停止线程
        }
        JOptionPane.showMessageDialog(this, "挖矿已停止！");
    }

    public static void main(String[] args) {
        // 在事件调度线程中启动应用程序
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                List<Map.Entry<String, String>> testList = new ArrayList<>(); // 空
                Map.Entry<String,String> test1 = Map.entry("publicKey", "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCCNIQ6cHSS/6VlOZbciZx0n+7GHGdAEitRcJmZ38OJj+Q==");
                Map.Entry<String,String> test2 = Map.entry("privateKey", "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUErt/vpIm0xbzEPuQvC5ZCx5PwOepVGzBZK5fRVQ3r4ROKZjFZbwOoLiW1wzhcbxBv7kNge3HWqY6VKlMLqGQw==");
                testList.add(test1);
                testList.add(test2);
                Chain chain = new Chain();
                new MineDialog(testList,chain).setVisible(true);
            }
        });
    }
}
